/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.sample.redis.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.cache.CacheService;
import org.moon.framework.autoconfigure.redis.RedisLock;
import org.moon.framework.autoconfigure.springmvc.response.R;
import org.moon.framework.sample.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis相关测试
 * @author moon
 */
@RestController
@Api(tags = "redis测试")
@Slf4j
public class MyController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private CacheService cacheService;

    @ApiOperation(value = "分布锁锁测试")
    @GetMapping(value = "/getByLock")
    public R<String> getByLock() {
        if (!redisLock.lock("lock_dis", "1")) {
            log.error("被锁住了...");
            return null;
        }
        try {
            return R.success("我使用的分布式锁");
        } finally {
            redisLock.unlock("lock_dis", "1");
            log.info("锁释放了...");
        }
    }

    @ApiOperation(value = "cacheService测试")
    @GetMapping(value = "/cacheService")
    public R<String> userCacheService(String key, String value) {
        cacheService.set(key, value);
        value = "我是从缓存里取出来的: " + cacheService.get(key);
        return R.success(value);
    }

    @ApiOperation(value = "springCache测试")
    @GetMapping(value = "/springCache")
    public R<String> springCache() {
        String v = redisService.getValueFromSpringCache();
        return R.success(v);
    }

    @ApiOperation(value = "stringRedisTemplate测试")
    @GetMapping(value = "/stringRedisTemplate")
    public R<String> stringRedisTemplate() {
        stringRedisTemplate.opsForValue().set("stringRedisTemplate", "我就是使用了stringRedisTemplate");
        String v = stringRedisTemplate.opsForValue().get("stringRedisTemplate");
        return R.success(v);
    }
}
